<?php
namespace app\admin\controller;

use \think\Request;
use \think\Db;
use \app\admin\model\AdminAccess as ModelAdminAccess;
use PHPExcel_IOFactory;
use PHPExcel;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class Base extends \app\common\controller\Base
{
    protected $res;
    /*
     * AdminModel的对象
     */
    protected $admin;
    protected $curAdmin;

    protected function admin()
    {
        if (is_null($this->admin)) {
            $this->admin = new \app\admin\model\Admin;
        }
        return $this->admin;
    }

    public function _initialize()
    {
        $this->chkLogin();
        if (!$this->check_access(session('admin')['role_id'])) {
            $this->error("您没有访问权限！");
            exit();
        }
//        print_r(session('admin')['id']);die;
        $this->forbiddenOutLogin();
        /*if(isset($this->res[Request::instance()->action()])){
            $cur_res = $this->res[Request::instance()->action()];
        }*/
        $curAction = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $fp = db('admin_menu')->where('action', $curAction)->value('path');
        $a = explode('-', trim($fp));
        array_pop($a);
        array_shift($a);
        array_shift($a);
        $bread = db('admin_menu')->where('action', $curAction)->value('name');
        if (!empty($a)) {
            foreach ($a as $b) {
                $bread_push[] = db('admin_menu')->where('id', $b)->value('name');
            }
            array_push($bread_push, $bread);
            $bread = $bread_push;
        }
        $this->assign(array(
            'curAdmin'  => cache('admin'),
            'curAvatar' => cache('admin')['avatar'],
            'bread'     => $bread,
            'res'       => isset($this->res[Request::instance()->action()]) ? $this->res[Request::instance()->action()] : null
        ));
    }

    /**
     * 检查登陆
     */
    protected function chkLogin()
    {
        $bacLoginPath = '/admin/login'; // 后台登陆页

        if (!$this->admin()->isLogin()) {
            $this->redirect(url($bacLoginPath));
        }
    }
    
    /**
     * 处于登录状态的时候，禁用跳转
     */
    public function forbiddenOutLogin(){
        $adminStatus = Db::name('admin')->where('id', session('admin')['id'])->find();//用于判断管理员状态
        $roleStatus = Db::name('admin_role')->where('id', $adminStatus['role_id'])->value('status');//用于判断角色状态
        if($adminStatus['status'] != 1){
            return $this->error('用户被禁用或删除', 'admin/login/logout');
        }
        if($roleStatus != 1){
            return $this->error('角色被禁用或删除', 'admin/login/logout');
        }
    }

    public function check_access($role_id)
    {
        /* 如果用户角色是1，则无需判断 */
        if ($role_id == 1) {
            return true;
        }
        $controller = strtolower(Request::instance()->controller());
        $action = strtolower(Request::instance()->action());
        //忽略的地址
        $ignore_array = array('login-index', 'index-index');
        if (in_array($controller . '-' . $action, $ignore_array)) {
            return true;
        }
        //如果是AJAX
        if (Request::instance()->isAjax()) {
            return true;
        }
        //暂时把所有的权限都放出来
        /*if (1 == 1) {
            if (session('admin')['id'] != 2) {
                return true;
            }
        }*/
        $aModel = new ModelAdminAccess();
        $res = $aModel->where("role_id = $role_id and controller = '" . $controller . "' and action = '" . $action . "'")->count();
//        echo $controller;
//        echo $action;
//        die;
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function search($search, $page, $fl = 'search')
    {
        if ($search === null && $page === null) {
            session($fl, null);
        } elseif ($search === '') {
            session($fl, null);
        } elseif ($search !== null) {
            session($fl, serialize($search));
        }
        return unserialize(session($fl));
    }
    /**
     * 对于状态的筛选条件建立
     */
    public function statusSelect($status,$fl = 'statusSelect'){
        if($status === null){
            session($fl,null);
        }elseif(trim($status) == ''){
            session($fl,null);
        }else{
            session($fl,serialize($status));
        }
        return unserialize(session($fl));
    }
    /**
     * 对时间信息进行通用的搜索
     */
    protected function getTimeMap(){
        $start = input('time_from');
        $end = input('time_to');
        $this->assign('time_from',$start);
        $this->assign('time_to',$end);
        $start = strtotime($start);
        $end = strtotime($end);
        if($start > 0 && $end > 0){
            $return = array('between',array($start,$end));
        }else if($start > 0){
            $return = array('gt',$start);
        }else if($end > 0){
            $return = array('lt',$end);
        }else{
            $return = array('gt',0);
        }
        return $return;
    }
    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
    function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }

    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    /**
     * @param $expTitle
     * @param $expCellName
     * @param $expTableData
     * @return \think\response\Json
     * excel导出
     */
    public function exportExcel($expCellName, $expTableData) {
        $name = date('_YmdHis');

        //$xlsTitle = iconv('utf-8', 'gb2312', $name);//文件名称
        //$fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $objPHPExcel = new PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $name.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$name.'.xls"');
        header("Content-Disposition:attachment;filename=$name.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $dir = ROOT_PATH . 'public' . DS . 'static/excel';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        function saveExcelToLocalFile($objWriter,$name){

            $filePath = 'static/excel/'.$name.'.xls';

            $filePath = iconv("utf-8", "gb2312", $filePath);
            $objWriter->save($filePath);
            return $name;
        }
        $name = saveExcelToLocalFile($objWriter,$name);
        return json(array('msg'=>'/static/excel/'.$name.'.xls','status'=>1));
        //$objWriter->save('php://output');
        //exit;

    }

    /**
     * @param $id
     * @return float|string
     * 根据身份证计算年龄
     */
    public function getAgeByID($id){
        //过了这年的生日才算多了1周岁
        if(empty($id)) return '';
        $date=strtotime(substr($id,6,8));
        //获得出生年月日的时间戳
        $today=strtotime('today');
        //获得今日的时间戳
        $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数

        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
        return $age;
    }

    public function qnCommon($rand,$exe,$filePath)
    {
        require_once ('../vendor/qiniu/autoload.php') ;
        if($exe != 'jpg' && $exe != 'gif' && $exe != 'png'&&$exe != 'jpeg'&&$exe != 'x-png'&&$exe != 'pjpeg') {
            $return = array('status' => 0, 'msg' => '请上传图片');
            return $return;
        }

        $accessKey = 'vN-QggRwoyeo6yBxxOPBamVG2ja2V2ANfzp-8v5k';
        $secretKey = 'NFWueX9frwxTQquf40Q2j7yL3VUD2BhJ6d37JiCR';
        $bucket = 'yi-dog';
        $auth = new Auth($accessKey, $secretKey);
        $returnBody = '{"key":"$(key)","mimeType":"$(mimeType)","vtime":"$(avinfo.video.duration)","atime":"$(avinfo.audio.duration)","fsize":$(fsize),"width":"$(imageInfo.width)","height":"$(imageInfo.height)","height":"$(imageInfo.height)","format":"$(imageInfo.format)"}';
        $policy = array(
            'returnBody' => $returnBody
        );
        $expires = 3600;
        $token = $auth->uploadToken($bucket, null, $expires, $policy, true);
        $key = $rand.'.'.$exe;
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            $info = $err;
        } else {
            $info = $ret;
        }
        $info['status'] = 200;
        return $info;
    }

    /**
     * @param $client
     * @param $sence
     * @param $orderId
     * @return array|bool
     * 极光推送
     */
    public function Jpush($token,$msg,$type,$msg_data){
        $ji=array(
            'appKey'=>'8614b01a9733364444c8c7d4',
            'masterSecret'=>'35a4e075f5d1ddcb4b3c25f3',
        );
        $client = new \JPush\Client($ji['appKey'],$ji['masterSecret']);
        $push = $client->push();
        $push->setPlatform('all');
        if($type==1){
            $push->addAlias($token);
        }else{
            $push->addAllAudience();
        }
        $push->iosNotification($msg, array(
                'alert'=>$msg,
                'badge' => '1',
                'extras' => $msg_data,
                'sound'=>'default'
            )
        );
        $push->androidNotification($msg, array(
            'badge' => '1',
            'extras' => $msg_data
        ));
        return $push->send();

    }

    public function sendCode($phone,$num){
        $body_json = array(
            'sid'=>'c22623fbab15f3fd208c123f772116f4',
            'token'=>'44b2970319a051f56c7309dcfe2ebef1',
            'appid'=>'a199f95f61f74e3abace3cff3cce7773',
            'templateid'=>$num,
            'param'=>'',
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    //获取年月日的数组
    public function prDates($start='',$end='',$type=''){
        if($type==1){//日
            $dt_start = strtotime($start);
            $dt_end = strtotime($end);
            while ($dt_start<=$dt_end){
                $array[] = date('Y-m-d',$dt_start);
                $dt_start = strtotime('+1 day',$dt_start);
            }
            return $array;

        }elseif ($type==2){//月
            $dt_start = strtotime($start);
            $dt_end = strtotime($end);
            while ($dt_start<=$dt_end){
                $array[] = date('Y-m',$dt_start);
                $dt_start = strtotime('+1 month',$dt_start);
            }
            return $array;

        }elseif ($type==3){//年
            $dt_start = date('Y', strtotime($start));
            $dt_end = date('Y', strtotime($end));
            while ($dt_start <= $dt_end) {
                $array[] = $dt_start;
                $dt_start = $dt_start+1;
            }
            return $array;

        }else{
            $time = time();
            $starts =  strtotime(date("Y-m-d", strtotime("-1 month")));
            while ($starts<=$time){
                $array[] = date('Y-m-d',$starts);
                $starts = strtotime('+1 day',$starts);
            }
            return $array;

        }
    }

    //获取年月日的数组
    public function prUserDate($start='',$end='',$type=''){
        if($type==1){//日
            $dt_start = strtotime($start);
            $dt_end = strtotime($end);
            while ($dt_start<=$dt_end){
                $array[] = date('Y-m-d',$dt_start);
                $dt_start = strtotime('+1 day',$dt_start);
            }
            return $array;

        }elseif ($type==2){//月
            $dt_start = strtotime($start);
            $dt_end = strtotime($end);
            while ($dt_start<=$dt_end){
                $array[] = date('Y-m',$dt_start);
                $dt_start = strtotime('+1 month',$dt_start);
            }
            return $array;

        }elseif ($type==3){//年
            $dt_start = date('Y', strtotime($start));
            $dt_end = date('Y', strtotime($end));
            while ($dt_start <= $dt_end) {
                $array[] = $dt_start;
                $dt_start = $dt_start+1;
            }
            return $array;
        }else{
            $time = time();
            $starts =  strtotime(date("Y-m-d", strtotime("-2 month")));
            while ($starts<=$time){
                $array[] = date('Y-m-d',$starts);
                $starts = strtotime('+1 day',$starts);
            }
            return $array;
        }
    }



















}
